package com.cqust;

import java.util.ArrayList;
import java.util.List;

public class ObserverPattern {
    public static void main(String[] args) {
        // 添加交通信号灯功能
        Subject trafficLight = new ConcreteTrafficLight();
        Observer car = new Car();
        Observer bus = new Bus();
        trafficLight.add(car);
        trafficLight.add(bus);
        ((ConcreteTrafficLight) trafficLight).changeColor("红色");
        ((ConcreteTrafficLight) trafficLight).changeColor("绿色");
    }
}

// 事件类 - 信号灯颜色
class TrafficLightEvent {
    private String color;

    public TrafficLightEvent(String color) {
        this.color = color;
    }

    public String getColor() {
        return color;
    }
}

// 抽象观察者接口
interface Observer {
    void response(TrafficLightEvent event); // 用于处理信号灯事件
}

// 具体观察者 - 轿车
class Car implements Observer {
    public void response(TrafficLightEvent event) {
        if ("红色".equals(event.getColor())) {
            System.out.println("红灯亮，轿车停！");
        } else if ("绿色".equals(event.getColor())) {
            System.out.println("绿灯亮，轿车行！");
        }
    }
}

// 具体观察者 - 公交车
class Bus implements Observer {
    public void response(TrafficLightEvent event) {
        if ("红色".equals(event.getColor())) {
            System.out.println("红灯亮，公交车停！");
        } else if ("绿色".equals(event.getColor())) {
            System.out.println("绿灯亮，公交车行！");
        }
    }
}

// 抽象目标类
abstract class Subject {
    protected List<Observer> observers = new ArrayList<>();

    // 增加观察者方法
    public void add(Observer observer) {
        observers.add(observer);
    }

    // 删除观察者方法
    public void remove(Observer observer) {
        observers.remove(observer);
    }

    public abstract void notifyObserver(TrafficLightEvent event); // 新增方法以处理信号灯事件
}

// 具体目标类 - 交通信号灯
class ConcreteTrafficLight extends Subject {
    public void changeColor(String color) {
        System.out.println(color + "信号灯亮...");
        System.out.println("--------------");
        TrafficLightEvent event = new TrafficLightEvent(color);
        notifyObserver(event);
    }

    @Override
    public void notifyObserver(TrafficLightEvent event) {
        for (Observer observer : observers) {
            observer.response(event);
        }
    }
}
